package com.china08.yxyapi.service.manage.tec.teaching.homework.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.WorklistFindV1Controller.Homework;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.WorklistFindV1Controller.ReqModel;
import com.china08.yxyapi.api.manage.tec.teaching.homework.worklist.WorklistFindV1Controller.RespModel;
import com.china08.yxyapi.entity.mg.homework.HomeworkTask;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskClass;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskClassRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.HomeworkListV1Service;
import com.china08.yxyapi.util.DateUtils;

@Service
public class HomeworkListV1ServiceImpl implements HomeworkListV1Service {

    @Autowired
    private HomeworkTaskClassRepository homeworkTaskClassRepository;

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    private HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    @Autowired
    private HomeworkTaskRepository homeworkTaskRepository;

    @Override
    public Date getPublishDate(ReqModel reqModel) throws ParseException {
        // 初始化处理
        if (reqModel.querytime == null) {
            reqModel.querytime = DateUtils.formatDate2(new Date());
        } else {
            reqModel.querytime = reqModel.querytime.replace("年", "-").replace("月", "-").replace("日", "");
            if (reqModel.querytime.contains("T") && reqModel.querytime.contains("Z")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                reqModel.querytime = reqModel.querytime.replace("Z", " UTC");
                Date date = format.parse(reqModel.querytime);
                reqModel.querytime = DateUtils.formatDate2(date);
            } else if (!reqModel.querytime.contains("-")) {
                reqModel.querytime = DateUtils.formatDate2(new Date());
            }
        }
        // 时间处理
        Date dateTime = DateUtils.formatStrDate(reqModel.querytime + " 23:59:59");
        if (reqModel.isDateDecrement != null && reqModel.isDateDecrement.equals("1")) { // 当前日期是否减一天
            dateTime = DateUtils.minusOneDay(dateTime);
            dateTime = DateUtils.formatStrDate(DateUtils.formatDate2(dateTime) + " 23:59:59");
        }
        // 获取 <= dateTime 的第一个有任务的时间
        HomeworkTaskClass homeworkTaskClass = null;
        // 学科判断
        if (reqModel.subjectId == null || reqModel.subjectId.trim().length() == 0 || reqModel.subjectId.equals("0")) {
            // 模糊查询(不带时间)
            if (reqModel.keyword != null && reqModel.keyword.trim().length() > 0) {
                // 指定某个班级模糊查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndTitleLikeAndClassIdAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.keyword, reqModel.classId,
                                    reqModel.stage);
                } else {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndTitleLikeAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.keyword, reqModel.stage);
                }
                // 非模糊查询
            } else {
                // 指定某个班级查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndClassIdAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.classId, reqModel.stage);
                } else {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.stage);
                }
            }
        } else {
            if (reqModel.keyword != null && reqModel.keyword.trim().length() > 0) {
                // 指定某个班级模糊查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndTitleLikeAndClassIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.keyword, reqModel.classId,
                                    reqModel.subjectId, reqModel.stage);
                } else {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndTitleLikeAndSubjectAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.keyword, reqModel.subjectId,
                                    reqModel.stage);
                }
                // 非模糊查询
            } else {
                // 指定某个班级查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndClassIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.classId, reqModel.subjectId,
                                    reqModel.stage);
                } else {
                    homeworkTaskClass = homeworkTaskClassRepository
                            .findTop1ByPublishDateLessThanEqualAndPublishUserIdAndSchoolIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateTime, reqModel.userId, reqModel.schoolId, reqModel.subjectId, reqModel.stage);
                }
            }
        }
        return homeworkTaskClass == null ? null : homeworkTaskClass.getPublishDate();
    }

    @Override
    public List<HomeworkTaskClass> findHomeworkTaskClass(ReqModel reqModel) throws ParseException {
        // 根据任务时间获取，当天教师发布任务列表
        Date dateStart = DateUtils.formatStrDate(DateUtils.formatDate2(reqModel.publishDate) + " 00:00:00");
        Date dateEnd = DateUtils.formatStrDate(DateUtils.formatDate2(reqModel.publishDate) + " 23:59:59");
        // ##
        List<HomeworkTaskClass> homeworkTaskClasss = null;
        if (reqModel.subjectId == null || reqModel.subjectId.trim().length() == 0 || reqModel.subjectId.equals("0")) {
            // 模糊查询(不带时间)
            if (reqModel.keyword != null && reqModel.keyword.trim().length() > 0) {
                // 指定某个班级模糊查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndTitleLikeAndClassIdAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.keyword,
                                    reqModel.classId, reqModel.stage);
                } else {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndTitleLikeAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.keyword,
                                    reqModel.stage);
                }
                // 非模糊查询
            } else {
                // 指定某个班级查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndClassIdAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.classId,
                                    reqModel.stage);
                } else {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.stage);
                }
            }
        } else {
            // 模糊查询(不带时间)
            if (reqModel.keyword != null && reqModel.keyword.trim().length() > 0) {
                // 指定某个班级模糊查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndTitleLikeAndClassIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.keyword,
                                    reqModel.classId, reqModel.subjectId, reqModel.stage);
                } else {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndTitleLikeAndSubjectAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.keyword,
                                    reqModel.subjectId, reqModel.stage);
                }
                // 非模糊查询
            } else {
                // 指定某个班级查询
                if (reqModel.classId != null && reqModel.classId.trim().length() > 0) {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndClassIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.classId,
                                    reqModel.subjectId, reqModel.stage);
                } else {
                    homeworkTaskClasss = homeworkTaskClassRepository
                            .findByPublishDateBetweenAndPublishUserIdAndSchoolIdAndSubjectAndStageOrderByPublishDateDesc(
                                    dateStart, dateEnd, reqModel.userId, reqModel.schoolId, reqModel.subjectId,
                                    reqModel.stage);
                }
            }
        }
        return homeworkTaskClasss;
    }

    @Override
    public RespModel convertRespModel(List<HomeworkTaskClass> homeworkTaskClasss) {
        // 判断是否为空
        if (homeworkTaskClasss == null || homeworkTaskClasss.size() == 0) { return null; }
        // return
        RespModel respModel = new RespModel();
        List<Homework> homeworks = new ArrayList<Homework>();
        // 获取当天时间
        HomeworkTaskClass HomeworkTaskClass = homeworkTaskClasss.get(0);
        // 日期输出
        respModel.year = String.valueOf(DateUtils.year(HomeworkTaskClass.getPublishDate()));
        respModel.month = String.valueOf(DateUtils.month(HomeworkTaskClass.getPublishDate()));
        respModel.day = String.valueOf(DateUtils.date(HomeworkTaskClass.getPublishDate()));
        respModel.week = String.valueOf(DateUtils.week(HomeworkTaskClass.getPublishDate()));
        respModel.dateTime = DateUtils.formatDate2(HomeworkTaskClass.getPublishDate());
        // ##
        for (HomeworkTaskClass homeworkTaskClass : homeworkTaskClasss) {
            Homework homework = new Homework();
            homework.taskId = homeworkTaskClass.getTaskId();
            homework.classId = homeworkTaskClass.getClassId();
            homework.title = homeworkTaskClass.getTitle();
            homework.grade = this.getGradeValue(homeworkTaskClass.getGrade());
            homework.className = homeworkTaskClass.getClassName();
            homework.totalPeople = homeworkTaskClass.getNumOfStudent() == null ? 0
                    : homeworkTaskClass.getNumOfStudent();
            homework.submitPeople = homeworkTaskClass.getSubmitOfStudent() == null ? 0
                    : homeworkTaskClass.getSubmitOfStudent();
            homework.readoverPeople = homeworkTaskClass.getMarkingOfStudent() == null ? 0
                    : homeworkTaskClass.getMarkingOfStudent();
            homework.submitRatio = String
                    .valueOf(getDouble(homeworkTaskClass.getSubmitOfStudent(), homeworkTaskClass.getNumOfStudent()))
                    .concat("%");
            homework.readoverRatio = String
                    .valueOf(getDouble(homeworkTaskClass.getMarkingOfStudent(), homeworkTaskClass.getSubmitOfStudent()))
                    .concat("%");
            List<HomeworkTaskReport> homeworkTaskReports = homeworkTaskReportRepository
                    .findByTaskIdAndClassIdOrderByMyRankingAsc(homeworkTaskClass.getTaskId(),
                            homeworkTaskClass.getClassId());
            homework.accuracy = this.getAverageRightRate(homeworkTaskReports);
            homework.accuracy = this.getAverageRightRate(homeworkTaskReports);
            homework.publishTime = DateUtils.formatDate3(homeworkTaskClass.getPublishDate());
            homework.predictDate = DateUtils.formatDate3(homeworkTaskClass.getPredictDate());
            homework.workStatus = this.getWorkStatus(homeworkTaskClass.getPublishDate(),
                    homeworkTaskClass.getPredictDate(), homeworkTaskClass.getNumOfStudent(),
                    homeworkTaskClass.getSubmitOfStudent(), homeworkTaskClass.getMarkingOfStudent());
            homework.timeStatus = this.getStatus(homeworkTaskClass.getPublishDate(),
                    homeworkTaskClass.getPredictDate());
            Integer count1 = homeworkTaskQuesRepository.countByTaskIdAndQuesType(homeworkTaskClass.getTaskId(), "2");
            homework.isNotify = count1 == null ? false : (count1 > 0 ? true : false);
            HomeworkTask homeworkTask = homeworkTaskRepository.findOne(homeworkTaskClass.getTaskId());
            homework.ifNeedSumbit = homeworkTask == null ? true
                    : homeworkTask.getIfNeedSumbit() == null ? true : homeworkTask.getIfNeedSumbit();
            Integer quesTotal = homeworkTaskQuesRepository.countByTaskId(homeworkTaskClass.getTaskId());
            homework.quesTotal = quesTotal == null ? 0 : quesTotal;
            homeworks.add(homework);
        }
        respModel.homeworks = homeworks;
        return respModel;
    }

    /** 获取平均值 **/
    public String getAverageRightRate(List<HomeworkTaskReport> homeworkTaskReport) {
        int count = 0;
        double rightRate = 0d;
        if (homeworkTaskReport != null && homeworkTaskReport.size() > 0) {
            for (int i = 0; i < homeworkTaskReport.size(); i++) {
                if (homeworkTaskReport.get(i).getRightRate() != null
                        && homeworkTaskReport.get(i).getStatusOfFinished() == 2) {
                    count++;
                    rightRate = rightRate + homeworkTaskReport.get(i).getRightRate();
                }
            }
        }
        if (count > 0) {
            if (rightRate <= 0) { return "0%"; }
            double x1 = this.getDouble(rightRate / count);
            String value = (((x1) + "00000").substring(0, 4) + "%").replace(".%", "%").replace(".0%", "%");
            if (value.equals("0.00%")) {
                return "0%";
            } else {
                return value;
            }
        } else {
            return "暂无";
        }
    }

    private Double getDouble(Double x1) {
        if (x1 == null) { return x1; }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.#");
        double parse = Double.parseDouble(df.format(x1));
        return parse;
    }

    /** 班级任务状态 **/
    private String getStatus(Date publishDate, Date predictDate) {
        // publishDate 发布时间
        // predictDate 截止时间
        // 比较两个时间大小： 前者大返回 1，前者小返回 -1，相等返回0
        int publishDiffmin = DateUtils.diffmin(new Date(), publishDate);
        // 比较两个时间大小： 前者大返回 1，前者小返回 -1，相等返回0
        int predictDiffmin = DateUtils.diffmin(new Date(), predictDate);
        // ##
        if (publishDiffmin == -1) {
            return "未开始";
        } else if (predictDiffmin >= 1) {
            return "已截止";
        } else {
            return "进行中";
        }
    }

    // 01年级~12年级
    public String getGradeValue(String grade) {
        if (grade == null) { return "暂无年级"; }
        grade = grade.toLowerCase();
        if (grade.equals("g1")) {
            return "一年级";
        } else if (grade.equals("g2")) {
            return "二年级";
        } else if (grade.equals("g3")) {
            return "三年级";
        } else if (grade.equals("g4")) {
            return "四年级";
        } else if (grade.equals("g5")) {
            return "五年级";
        } else if (grade.equals("g6")) {
            return "六年级";
        } else if (grade.equals("g7")) {
            return "七年级";
        } else if (grade.equals("g8")) {
            return "八年级";
        } else if (grade.equals("g9")) {
            return "九年级";
        } else if (grade.equals("g10")) {
            return "高一";
        } else if (grade.equals("g11")) {
            return "高二";
        } else if (grade.equals("g12")) {//
            return "高三";//
        } else if (grade.equals("gc4")) {//
            return "九年级";//
        } else if (grade.equals("g_xq")) {//
            return "学前班";//
        } else if (grade.equals("g0_0")) {//
            return "幼儿园小小班";//
        } else if (grade.equals("g0_1")) {//
            return "幼儿园小班";//
        } else if (grade.equals("g0_2")) {//
            return "幼儿园中班";//
        } else if (grade.equals("g0_3")) {//
            return "幼儿园大班";//
        }
        return grade;
    }

    /**
     * 作业状态
     * 
     * @param publishDate
     *            发布时间
     * @param predictDate
     *            截止时间
     * @param numOfStudent
     *            本班级，参与此任务的人数
     * @param submitOfStudent
     *            作业提交人数
     * @param markingOfStudent
     *            已经批阅人数
     * @return 作业状态 1 已批阅、2 未批阅、 3 批阅中
     */
    private int getWorkStatus(Date publishDate, Date predictDate, Integer numOfStudent, Integer submitOfStudent,
            Integer markingOfStudent) {
        // 参与任务人数为0, 为未批阅
        if (numOfStudent <= 0) { return 2; }
        // 比较两个时间大小： 前者大返回 1，前者小返回 -1，相等返回0
        int publishDiffmin = DateUtils.diffmin(new Date(), publishDate);
        if (publishDiffmin == -1) {
            // 未开始
            return 2; // 未批阅
        } else {
            // 比较两个时间大小： 前者大返回 1，前者小返回 -1，相等返回0
            int predictDiffmin = DateUtils.diffmin(new Date(), predictDate);
            if (predictDiffmin >= 1) {
                // 已截止
                if (markingOfStudent > 0) {
                    if (numOfStudent == markingOfStudent || submitOfStudent == markingOfStudent) {
                        return 1; // 1 已批阅
                    } else {
                        return 3; // 3 批阅中
                    }
                } else {
                    if (submitOfStudent == 0) {
                        return 2; // 未批阅
                    } else {
                        return 3; // 3 批阅中
                    }
                }
            } else {
                // 进行中
                if (markingOfStudent == 0) {
                    return 2; // 未批阅
                } else {
                    if (numOfStudent == markingOfStudent) {
                        return 1; // 1 已批阅
                    } else {
                        return 3; // 3 批阅中
                    }
                }
            }
        }
    }

    /** 百分比转化 **/
    private double getDouble(Integer x1, Integer sum) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.###");
        if (x1 == null || sum == null) {//
            return 0d;
        } else if (x1 <= 0 || sum <= 0) {//
            return 0d;
        } else {
            double d = (x1 * 0.1) / (sum * 0.1);
            return Double.parseDouble(df.format(d)) * 100;
        }
    }
}
